//////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
(function($) {
    yiaCtx.storage = {
        set: function(key, value) {
            localStorage.setItem(key, JSON.stringify(value))
        },
        get: function(key) {
            return JSON.parse(localStorage.getItem(key))
        },
        remove: function(key) {
            localStorage.removeItem(key)
        }
    }

    yiaCtx.validator = {
        checkEmail: function(email) {
            return email && /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(email)
        }
    }

    // type: 提示类型
    // content: 显示内容
    yiaCtx.notice = function(content, type, width) {
        type  = type ? type : 'info'
        width = width ? width : 'auto'

        if(['info', 'warning', 'error', 'success'].indexOf(type) == -1) {
            throw 'notice type error！'
        }

        if(!content) return

        if( !$('.yia-notice').length ){
            $('body').append('<div class="yia-notice" style="min-width: ' + width + '"></div>')
        } else {
            var rClass = 'notice-success notice-warning notice-error notice-info'
            $('.yiaos-notice').removeClass(rClass).addClass('notice-' + type)
        }
        $('.yia-notice').stop(true).html( tboslang[content] || content ).fadeIn().delay(2000).fadeOut()
    }

    yiaCtx.copy = function (val) {
        var ipt = document.createElement('input')
        ipt.setAttribute('readonly', 'readonly')
        ipt.setAttribute('value', val)
        document.body.appendChild(ipt)
        ipt.select()
        if (document.execCommand('copy')) {
            document.execCommand('copy')
        }
        document.body.removeChild(ipt)
    }

    yiaCtx.event.copy_link = function (ele) {
        ele.addClass('disabled -a')
        yiaCtx.copy(window.location.href)
        yiaCtx.notice(tboslang['1030']);
        setTimeout(function() {
            ele.removeClass('disabled -a')
        }, 500)
    }
})(jQuery);

//////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
(function($) {
    window.Swiper = null

    function loadSwiper(callback) {
        if(!Swiper) {
            $.getScript(yiaCtx.jsCdn + '/static/js/libs/swiper.min.js', function() {
                callback()
            })
        } else {
            callback()
        }
    }

    if($('.yia-swiper').length) {
        loadSwiper(function() {
            new Swiper('.yia-swiper', {
                loop: true,
                speed: 800,
                autoplay: {
                    delay: 3000,
                    disableOnInteraction: false
                },
                pagination: {
                    el: '.swiper-pagination',
                    clickable: true,
                },
                navigation: {
                    nextEl: '.swiper-next',
                    prevEl: '.swiper-prev',
                }
            })
        })
    }

    function init_article_swiper() {
        if(!yiaCtx.article_swiper) return

        var article_c = $('.article-content')
        if(!article_c.length) return

        var img_arr = article_c.find('img')
        if(!img_arr.length) return
        
        loadSwiper(function() {
            img_arr.on('click', function() {
                var active = $(this).attr('src')
                var index = article_swiper_render(active, img_arr)
                
                new Swiper('.yia-article-swiper', {
                    loop: false,
                    speed: 800,
                    zoom: true,
                    initialSlide: index,
                    navigation: {
                        nextEl: '.swiper-next',
                        prevEl: '.swiper-prev',
                    },
                    pagination: {
                        el: '.swiper-pagination',
                        type: 'fraction'
                    },
                    on: {
                        slideNextTransitionStart: function() {
                            $('.yia-article-swiper .swiper-slide-prev img').addClass('yia-swiper-no-transition')
                        },
                        slidePrevTransitionStart: function() {
                            $('.yia-article-swiper .swiper-slide-next img').addClass('yia-swiper-no-transition')
                        },
                        slideChange: function() {
                            $('.yia-article-swiper .yia-swiper-no-transition').removeClass('yia-swiper-no-transition')
                        }
                    }
                })
            })
        })
    }

    function article_swiper_render( active, img_arr ) {
        var swiper_items = ''
        var index = 0
        img_arr.each(function(i, item) {
            var src = $(item).attr('src')
            if(active == src) {
                index = i
            }
            swiper_items += '<div class="swiper-slide swiper-item">'
            swiper_items += '<div class="swiper-zoom-container">'
            swiper_items += '<img alt="swiper" src="' + src + '" />'
            swiper_items += '</div>'
            swiper_items += '</div>'
        });

        var wraper = $('.yia-article-modal')
        if(wraper.length) {
            wraper.find('.swiper-wrapper').html(swiper_items)
        } else {
            var swiper = '<div class="yia-article-modal">'

            swiper += '<div class="modal-mask" data-event="hide_article_modal"></div>'

            swiper += '<span class="yiafa icon-close" data-event="hide_article_modal">&#xe8e0;</span>'

            swiper += '<div class="yia-article-swiper">'
            swiper += '<div class="swiper-wrapper swiper-inner">' + swiper_items + '</div>'
            swiper += '<div class="swiper-nav swiper-prev"><i class="yiafa icon-forward">&#xe8cf;</i></div>'
            swiper += '<div class="swiper-nav swiper-next"><i class="yiafa icon-back">&#xe8d2;</i></div>'
            swiper += '<div class="swiper-pagination"></div>'
            swiper += '</div>'

            swiper += '</div>'

            $('body').append(swiper)
        }
        
        yiaCtx.event.toggle_scroll('hide')
        $('.yia-article-modal').show()

        return index
    }
    init_article_swiper()

    yiaCtx.event.hide_article_modal = function() {
        yiaCtx.event.toggle_scroll('show')
        $('.yia-article-modal').hide()
    }
})(jQuery);

//////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
(function($) {
    // body 适配
    var header_h_cache = 68
    function auto_wraper() {
        if(!yiaCtx.h_fixed) {
            return
        }
        var h = $('header.header').outerHeight()
        if(h != header_h_cache) {
            setTimeout(function() {
                header_h_cache = h
                $('body').css('padding-top', $('header.header').outerHeight())
            }, 100)
        }
    }

    auto_wraper()
    
    
    // 嵌入iframe自适应
    function auto_iframe() {
        var resize_arr = []
        var article_wraper = $('.article')
        var iframe = article_wraper.find('iframe')
        if(article_wraper.length && iframe.length) {
            iframe.each(function(i, ele) {
                var _this = $(ele)

                // 宽度为百分比时不适配
                var iframe_w = _this.attr('width')
                if(!(iframe_w && /%$/g.test(iframe_w))) {
                    var iframe_h = _this.attr('height') ? parseInt(_this.attr('height')) : _this.outerHeight()
                    iframe_w = iframe_w ? parseInt(iframe_w) : _this.outerWidth()
                    resize_arr.push({
                        ele: _this,
                        h: iframe_h,
                        w: iframe_w
                    })
                    _this.attr('height', _this.width() / iframe_w * iframe_h)
                }
            })
        }
        
        var resize_iframe = function() {
            resize_arr.length && resize_arr.forEach(function(item) {
                item.ele.attr('height', item.ele.width() / item.w * item.h)
            })
        }
        return resize_iframe
    }
    var resize_iframe = auto_iframe()


    $(window).resize(function() {
        auto_wraper()
        resize_iframe()
    })
})(jQuery);

//////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
(function($) {
    function time_diff_format($text) {
        if(yiaCtx.comment_tf == 'time_diff') {
            var maps = {'1017': '分钟前', '1018': '秒前', '1019': '刚刚'}

            for (var key in maps) {
                $text = $text.replace(maps[key], tboslang[key])
            }
        }
        
        return $text
    }

    function installComment() {
        var loading = false
        var commentform = $('#commentform')
        commentform.submit(function(){
            if(loading) return false
            loading = true

            $('.yia-primary-btn').val(tboslang['1001'])

            var form = {
                action: 'add_comment'
            }
            var data = $(this).serializeArray()
            $.each(data, function() {
                form[this.name] = this.value;
            });

            var error_code = ''
            var code_l   = $(this).find('[name="code"]').length
            if(code_l && (!form.code || Number(form.code) != Number(form.code1) + Number(form.code2) ) ) {
                error_code = 1020
            }

            if(!error_code && !form.comment) {
                error_code = 1012
            }

            if(!error_code && form.hasOwnProperty('author') && !form.author) {
                error_code = 1013
            }

            if(!error_code && form.hasOwnProperty('email') && (!form.email || !yiaCtx.validator.checkEmail(form.email))) {
                error_code = 1014
            }

            if(error_code) {
                yiaCtx.notice(error_code)
                loading = false
                $('.yia-primary-btn').val(tboslang['1002'])
                return false
            }
    
            $.ajax({
                url: yiaCtx.ajaxUri,
                type: 'POST',
                dataType: 'json',
                data: form,
                success: function(res, textStatus) {
                    if(!res.result) {
                        loading = false
                        $('.yia-primary-btn').val(tboslang['1002'])
                        yiaCtx.notice(res.errormsg, 'error')
                    } else {
                        $('#comment').val('')
                        $('#comment_parent').val('0')
                        $('#cancel-comment-reply-link').css('display','none')
                        $('#wp-temp-form-div').replaceWith($('#respond'))
                        loading = false
                        $('.yia-primary-btn').val(tboslang['1002'])

                        if(code_l) {
                            commentform.find('[name="code"]').val('')
                            var code1 = Math.floor(Math.random()*9+1)
                            var code2 = Math.floor(Math.random()*9+1)
                            commentform.find('.c-code span').html(code1+' + '+code2+' =')
                            commentform.find('[name="code1"]').val( code1 )
                            commentform.find('[name="code2"]').val( code2 )
                        }
                        
                        var approvedText = res.data.comment_approved === '0' ? '<span class="item-user-status">' + tboslang['1003'] + '</span>' : ''
                        var depth = 1
                        var replyLink = ''
                        var depthReg = /depth-[0-9]+/
                        if(['0', 0].indexOf(res.data.comment_parent) == -1) {
                            var class_str =  $('#comment-' + res.data.comment_parent).attr('class')
                            $.each(class_str.split(' '), function(i, item) {
                                if(depthReg.test(item)) {
                                    depth = parseInt(item.split('-')[1]) + 1
                                }
                            })
                        }
                        if(depth < res.data.max_depth && res.data.comment_approved === '1') {
                            replyLink = '<a rel="nofollow" class="comment-reply-link" href="javascript:;" data-commentid="' + res.data.comment_ID + '" data-postid="' + res.data.comment_post_ID + '" data-belowelement="comment-main-' + res.data.comment_ID + '" data-respondelement="respond">' + tboslang['1004'] + '</a>'
                        }
                        comment_class = res.data.comment_class.replace(depthReg, 'depth-' + depth)
                        
                        var commentEle = '<li ' + comment_class + 'id="comment-' + res.data.comment_ID + '">' +
                                            '<div class="comment-main" id="comment-main-' + res.data.comment_ID + '">' +
                                                '<div class="item-left">' + 
                                                    '<img class="item-avatar" src="'+ res.data.comment_author_avatar + '" alt="avatar">' +
                                                '</div>' +
                                                '<div class="item-right">' +
                                                    '<div class="item-user">' + 
                                                        (res.data.comment_author_url ? '<a class="i-u-name" rel="external nofollow ugc" href="' + res.data.comment_author_url + '">' + res.data.comment_author_name + '</a>' : '<span class="item-user-item">' + res.data.comment_author_name + '</span>') +
                                                        '<span class="item-user-item">' + time_diff_format(res.data.comment_date) + '</span>' +
                                                        approvedText + 
                                                        replyLink +
                                                    '</div>' +
                                                    '<p class="item-text">' + res.data.comment_content + '</p>' +
                                                '</div>' +
                                            '</div>' +
                                        '</li>'
                        var commentsList = $('.comments-list')
                        if(res.data.comment_parent === '0') {
                            if(commentsList.length) {
                                commentsList.append(commentEle)
                            } else {
                                $('#respond').after('<ol class="comments-list">' + commentEle + '</ol>')
                            } 
                        } else {
                            var childEle = $('#comment-' + res.data.comment_parent + ' > .children')
                            if(childEle.length) {
                                childEle.append(commentEle)
                            } else {
                                $('#comment-' + res.data.comment_parent + ' > .comment-main').after('<ul class="children">' + commentEle + '</ul>')
                            }
                        }
                    }
                },
                error: function(xhr, str, err) {
                    loading = false
                    $('.yia-primary-btn').val(tboslang['1002'])
                    yiaCtx.notice(JSON.stringify(err), 'error')
                }
            })
            return false
        })
    }
    $('.comments-container').length && installComment()
})(jQuery);


//////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
(function($) {
    yiaCtx.event.tougao = function (ele) {
        var form = {
            action: 'yia_tougao'
        }
        var data = $('#tougao').serializeArray()
        $.each(data, function() {
            form[this.name] = $.trim(this.value);
        });

        var error_code = ''
        if( !window.tinyMCE ){
            error_code = 1029
        } else {
            form.content = $.trim(tinyMCE.activeEditor.getContent())
        }
        
        if(!error_code && (!form.title || form.title.length > 50)) {
            error_code = 1023
        }
        
        if(!error_code && (!form.content || form.content.length < 10 || form.content.length > 10000)) {
            error_code = 1024
        }
        
        if(error_code) {
            yiaCtx.notice(error_code)
            return
        }

        $.ajax({
            url: yiaCtx.ajaxUri,
            type: 'POST',
            dataType: 'json',
            data: form,
            success: function(res) {
                yiaCtx.notice(res.msg, 'info')

                if(res.result) {
                    setTimeout(function() {
                        location.href = ele.attr('data-home')
                    }, 2000);
                }
            }
        })
    }
})(jQuery);


//////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
(function($) {
    yiaCtx.like_install = install
    yiaCtx.event.like   = handleLike

    var likes = $('.yia-like')
    if(likes.length) {
        install(likes)
    }

    function install(likes) {
        var likeArr = yiaCtx.storage.get('like') || []
        likes.each(function(i, ele) {
            var jEle = $(ele)

            if(likeArr.indexOf(jEle.data("id")) != -1) {
                jEle.find('i').removeClass('icon-like').addClass('icon-like-active').text("\ue600")
            }
        })
    }

    function handleLike(ele) {
        ele.addClass('disabled')

        var post_id      = ele.data("id")
        var likeArr      = yiaCtx.storage.get('like') || []
        var count_action = 1

        if(likeArr.indexOf(post_id) != -1) {
            count_action = -1
            likeArr      = likeArr.filter(function(item) {
                return item !== post_id
            })
        } else {
            likeArr.push(post_id)
        }
        
        $.ajax({
            url: yiaCtx.ajaxUri,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'yia_updata_like',
                post_id: post_id,
                count_action: count_action
            },
            success: function(data, textStatus) {
                yiaCtx.storage.set('like', likeArr)

                var icon = '<i class="yiafa icon-like">&#xe60d;</i>'
                if(count_action == 1) {
                    icon = '<i class="yiafa icon-like-active">&#xe600;</i>'
                }
                
                ele.html(icon + data.count + (ele.attr('data-suffix') ? ' ' + ele.attr('data-suffix') : '')).removeClass('disabled')

                data.like_msg && yiaCtx.notice(data.like_msg, 'success', '220px')
            },
            error: function(xhr, str, err) {
                ele.removeClass('disabled')
            }
        })
    }
})(jQuery);

//////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
(function($) {
    var box = $('.social-share')

    yiaCtx.shareInfo = {
        link: document.URL,
        title: document.title,
        desc: $('meta[name="description"]').length ? $('meta[name="description"]').attr("content") : "",
        imgUrl: yiaCtx.share_img
    }
    
    if($('body').hasClass('mobile-share-on')) {
        var url = location.href.split('#')[0]
        getAccessToken(url).done(function(res) {
            if(res.result) {
                $.getScript('https://res.wx.qq.com/open/js/jweixin-1.6.0.js', function() {
                    sdkShare()
                })
            }
        })
    }
    
    if(box.length) {
        yiaCtx.event.share        = handleShare
        yiaCtx.event.qrcode_close = closeQrcode
    }

    function getAccessToken(url) {
        return $.ajax({
            url: yiaCtx.ajaxUri,
            type: 'GET',
            data: {
                action: 'wx_signature',
                url: url
            },
            dataType: 'json',
            success: function(data) {
                if(data.result) {
                    window.yiaCtx.wx = {
                        appId: yiaCtx.appID,
                        timestamp: data.info.timestamp,
                        nonceStr: data.info.nonceStr,
                        signature: data.info.signature
                    }
                }
            }
        })
    }

    function sdkShare() {
        wx.config({
            debug: false,
            appId: yiaCtx.appID,
            timestamp: yiaCtx.wx.timestamp,
            nonceStr: yiaCtx.wx.nonceStr,
            signature: yiaCtx.wx.signature,
            jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData', 'onMenuShareWeibo']
        });
        
        wx.ready(function() {
            wx.updateAppMessageShareData(yiaCtx.shareInfo)
            wx.updateTimelineShareData(yiaCtx.shareInfo)
            wx.onMenuShareWeibo(yiaCtx.shareInfo)
        })
    }
    
    function handleShare(ele) {
        var type = ele.data('type')
        var url = ''
        switch(type) {
            case 'qq':
                url = 'http://connect.qq.com/widget/shareqq/index.html?url=' + yiaCtx.shareInfo.link + '&title=' + yiaCtx.shareInfo.title +'&desc=' + yiaCtx.shareInfo.desc +'&pics='+ yiaCtx.shareInfo.imgUrl +'&summary=' + yiaCtx.shareInfo.title
                break
            case 'weibo':
                url = 'https://service.weibo.com/share/share.php?url=' + yiaCtx.shareInfo.link +'&title=' + yiaCtx.shareInfo.title +'&pic='+ yiaCtx.shareInfo.imgUrl
                break
            case 'wechat':
                var qrcode_modal = '<div class="qrcode">'
                qrcode_modal += '<div class="qrcode-mask" data-event="qrcode_close"></div>'
                qrcode_modal += '<div class="qrcode-in yia-rds4">'
                qrcode_modal += '<i class="yiafa icon-close" data-event="qrcode_close">&#xe8e0;</i>'
                qrcode_modal += '<img alt="qrcode" src="http://api.asilu.com/qrcode/?t=' + yiaCtx.shareInfo.link + '">'
                qrcode_modal += '<p>' + tboslang['1009'] + '</p>'
                qrcode_modal += '</div>'
                qrcode_modal += '</div>'

                $(".qrcode").length || $("body").append(qrcode_modal)

                $(".qrcode").show().find(".qrcode-in").animate({
                    top: "50%",
                    opacity: 1
                }, 500)

                yiaCtx.event.toggle_scroll('hide')

                break
            case 'douban':
                url = 'http://shuo.douban.com/!service/share?href=' + yiaCtx.shareInfo.link + '&name=' + yiaCtx.shareInfo.title +'&tyia=' + yiaCtx.shareInfo.desc +'&image='+ yiaCtx.shareInfo.imgUrl
                break
            case 'qzone':
                url = 'http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=' + yiaCtx.shareInfo.link + '&title=' + yiaCtx.shareInfo.title +'&desc=' + yiaCtx.shareInfo.desc + '&pics='+ yiaCtx.shareInfo.imgUrl
                break
            case 'line':
                url = 'http://line.naver.jp/R/msg/text/?' + yiaCtx.shareInfo.title + '%0D%0A' + yiaCtx.shareInfo.link
                break
            case 'twitter':
                url = 'https://twitter.com/intent/tweet?text=' + yiaCtx.shareInfo.title + '&url=' + yiaCtx.shareInfo.link
                break
            case 'facebook':
                url = 'https://www.facebook.com/sharer/sharer.php?u=' + yiaCtx.shareInfo.link + '&title=' + yiaCtx.shareInfo.title + '&description=' + yiaCtx.shareInfo.desc
                break
            case 'telegram':
                url = 'https://telegram.me/share/url?text=' + yiaCtx.shareInfo.title + '&url=' + yiaCtx.shareInfo.link
                break
            case 'skype':
                url = 'https://web.skype.com/share?text=' + yiaCtx.shareInfo.title + '&url=' + yiaCtx.shareInfo.link
                break
            case 'copy':
                yiaCtx.event.copy_link(ele)
                break
        }
    
        url && window.open(url)
    }

    function closeQrcode() {
        $('.qrcode-in').animate({
            top: "100%",
            opacity: 0
        }, 500, function() {
            $('.qrcode').hide()
            yiaCtx.event.toggle_scroll('show')
        })
    }
})(jQuery);

//////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
(function($) {
    var thumbs = $('.thumbs-item img')
    var avatar_w = $('.comment-item .item-avatar')
    var avatar_c = $('.comment-main .item-avatar')
    if(thumbs.length || avatar_w.length || avatar_c.length) {
        $.getScript(yiaCtx.jsCdn + '/static/js/libs/lazyload.min.js', function() {
            yiaCtx.lazyload(thumbs)
            yiaCtx.lazyload(avatar_w, 'avatar')
            yiaCtx.lazyload(avatar_c, 'avatar')
        })
    }

    yiaCtx.lazyload = function(ele, type) {
        if(!ele.length) return
        type = type ? type : 'thumb'

        function lazy() {
            ele.lazyload({
                data_attribute: 'src',
                placeholder: yiaCtx['default_' + type],
                threshold: 300,
                failure_limit: 50 
            })
        }
        
        if(ele.lazyload) {
            lazy()
        } else {
            $.getScript(yiaCtx.jsCdn + '/static/js/libs/lazyload.min.js', function() {
                lazy()
            })
        }
    }
})(jQuery);

//////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
(function($) {
    var gap = 24
    var article_loading = false
    var prev_catalog_id = ''
    var catalog_h = 32
    var is_single = $('body').hasClass('single') || $('body').hasClass('page')

    // 回到顶部
    yiaCtx.event.scroll_top = function() {
        $('html,body').animate({scrollTop: 0}, 300)
    }

    function taggleScrollTop(scrollTop) {
        var scrollEle = $('.scroll-top')

        if(scrollTop > 300) {
            scrollEle.css({
                opacity: 1
            })
        } else {
            scrollEle.css({
                opacity: 0
            })
        }
    }


    // 文章目录
    yiaCtx.event.catalog_scroll = function(ele) {
        ele.addClass('active').siblings().removeClass('active')
        yiaCtx.event.hide_catalog_modal()
    }

    function theme_catalogs() {
        if(!is_single) {
            return ''
        }

        var catalog = $('.yia-catalog')
        if(!catalog.length) {
            return ''
        }
        
        var title_ele = $('.article-content').find(':header')
        var len = title_ele.length

        if(!len) {
            return ''
        }

        return {
            ele: title_ele,
            len: title_ele.length
        }
    }

    // 滚动时高亮对应目录
    function catalog_scroll_active(scrollTop) {
        var obj = theme_catalogs()
        if(!obj) {
            return
        }
        
        var active_id = null
        obj.ele.each(function(i) {
            var next = i < obj.len -1 ? obj.ele[i + 1] : null
            
            if(next) {
                if($(next).offset().top - 1 >= scrollTop) {
                    active_id = $(this).attr('id')
                    return false
                }
            } else {
                active_id = $(this).attr('id')
                return false
            }
        })

        if(active_id && prev_catalog_id == active_id) {
            return
        }
        
        prev_catalog_id = active_id
        catalog_item_scroll(active_id)
    }

    function catalog_item_scroll(active_id) {
        var catalog = $('.catalog-list')
        var active_ele = catalog.find('.catalog-item[data-id="' + active_id + '"]')
        // catalog_h = !catalog_h ? active_ele.outerHeight() : catalog_h
        active_ele.addClass('active').siblings().removeClass('active')
        var count = parseInt(active_id.split('-')[1])
        $('.catalog-list').animate({scrollTop: catalog_h * (count - 1)}, 100)
        $('.catalog-dot').animate({top: catalog_h * (count + 0.5) - 4}, 100)
    }

    // 初始化时定位到所在锚点
    yiaCtx.event.init_catalog_anchor = function () {
        if(!theme_catalogs()) {
            return
        }

        if($('.yia-catalog.widget-on-phone').length) {
            $('.site-tools').prepend('<div class="tools-icon -catalog" data-event="show_catalog_modal"><i class="yiafa icon-mulu">&#xe8e5;</i></div>')
        }

        history.scrollRestoration = 'manual'
        
        var offset = 0
        var active_id = '#title-0'
        if(window.location.hash) {
            active_id = window.location.hash
            var title = $('.article-content').find(active_id)
            offset = title.length ? title.offset().top : 0
            offset && $('html,body').scrollTop(offset)
        } else {
            $('html,body').scrollTop(offset)
        }
        
        catalog_item_scroll(active_id.replace('#', ''))
    }

    yiaCtx.event.show_catalog_modal = function() {
        var catalog_modal = $('.-catalog-modal')
        if(!catalog_modal.length) {
            var mulu_modal = '<div class="tb-modal -catalog-modal">'
            mulu_modal += '<div class="-mask" data-event="hide_catalog_modal"></div>'
            mulu_modal += '<i class="yiafa icon-close" data-event="hide_catalog_modal">&#xe8e0;</i>'
            mulu_modal += '<div class="m-inner -b yia-rds4">'
            mulu_modal += $('.yia-catalog')[0].innerHTML
            mulu_modal += '</div>'
            mulu_modal += '</div>'

            $('body').append(mulu_modal)

            // 首次打开弹窗时，滚动到目标位置
            prev_catalog_id = ''
        }

        yiaCtx.event.toggle_scroll('hide')
        $('.-catalog-modal').addClass('active')
        catalog_scroll_active(document.documentElement.scrollTop || document.body.scrollTop)
    }

    yiaCtx.event.hide_catalog_modal = function() {
        yiaCtx.event.toggle_scroll('show')
        var catalog_modal = $('.-catalog-modal')
        if(catalog_modal.length) {
            $('.-catalog-modal').removeClass('active')
        }
    }

    // 侧栏随动
    function sideRollInit(gap) {
        var sidebar = $('.sidebar')
        var roll = sidebar.attr('data-roll') ? sidebar.attr('data-roll').split(' ') : []
        var is_phone = $('body').hasClass('is-phone')
        var items = sidebar.children('.widget')
        var fixed_h = 0
        for (var i = 0; i < roll.length; i++) {
            roll[i] = parseInt(roll[i])
            var dom = items.eq(roll[i]-1)
            if( !dom.length ){
                break
            }
            fixed_h += dom.outerHeight(true)
        }
        return {
            fst_offset_top: items.length ? items.eq(Math.min.apply(null, roll) - 1).offset().top : 0,
            canRoll: sidebar.length && roll.length && items.length && !is_phone,
            sidebar: sidebar,
            side_h: sidebar.height() - gap,
            roll: roll,
            items: items,
            fixed_h: fixed_h
        }
    }

    function scrollHandle(handle) {
        $(window).scroll(function() {
            var scrollTop =  document.documentElement.scrollTop || document.body.scrollTop
            handle(scrollTop)
        })
    }


    // 触底自动加载文章
    function autoLoadArticle(scrollTop) {
        if(!$('.post-list').length) return
        
        var last_post = $('.post-list .post-item:last-child')
        if(!last_post.length) return

        var offsetTop = last_post.offset().top
        var last_post_height = last_post.outerHeight()
        var body_height = $(window).height()
        var auto_load = $('.yia-auto-paginate')
        
        if(auto_load.attr('data-href') && scrollTop + body_height >= offsetTop + last_post_height) {
            
            // 超过最大加载页数
            var max = auto_load.attr('data-max')
            if(!(max && parseInt(max) <= parseInt(auto_load.attr('data-current')))) {
                yiaCtx.event.load_posts(auto_load)
            }
        }
    }

    yiaCtx.event.load_posts = function (ele) {
        if(article_loading) return
        article_loading = true

        ele.find('.yia-load-more').hide()
        ele.find('.yia-spin').css({display: 'inline-block'})

        var next_url = ele.attr('data-href')
        $.ajax({
            type: 'get',
            url: next_url,
            success: function(data) {
                
                var list = $(data).find('.post-list .post-item')
                var likes = list.find('.yia-like')
                likes.length && yiaCtx.like_install(likes)

                var next_link = $(data).find('.yia-auto-paginate').attr('data-href')
                if(next_link) {
                    ele.attr('data-href', next_link)
                    ele.attr('data-current', $(data).find('.yia-auto-paginate').attr('data-current'))
                    ele.attr('data-event', $(data).find('.yia-auto-paginate').attr('data-event'))
                    
                    ele.find('.yia-load-more').show()
                    ele.find('.yia-spin').hide()
                } else {
                    ele.attr('data-event', '')
                    ele.attr('data-href', '')
                    ele.find('.yia-load-more').hide()
                    ele.find('.yia-spin').hide()
                    ele.find('.yia-no-more').show()
                }
                $('.post-list').append(list)
                article_loading = false

                autoLoadArticle(0)
                
                yiaCtx.lazyload(list.find('.thumbs-item img'))
            }
        })
    }


    function sideRollHandle(scrollTop, side, gap) {
        var doc_h = $(document).height()
        var side_top = side.sidebar.offset().top
        var footer_h = $('.footer').outerHeight()
        var header_h = yiaCtx.h_fixed ? $('header.header').outerHeight() : 0
        var side_top_menu = side_top - header_h

        function side_t_b() {
            var top = 0
            for (var i = 0; i < side.roll.length; i++) {
                var dom = side.items.eq(side.roll[i]-1)
    
                if( !dom.length ){
                    break
                }
                
                if( scrollTop > doc_h - footer_h - header_h - gap - side.fixed_h ){
                    dom.removeClass('yia-fix-top').addClass('yia-fix-bottom').css('top', doc_h - footer_h - header_h - side.fixed_h - side_top_menu + top)
                } else {
                    dom.removeClass('yia-fix-bottom').addClass('yia-fix-top').css('top', header_h + gap + top)
                }
                top += dom.outerHeight(true)
            }
        }
        
        if(yiaCtx.sidebar_fix_on == 'all' || (yiaCtx.sidebar_fix_on == 'single' && is_single)) {
            if($(document).width() <= 1024) {
                return
            }

            if(scrollTop > side.fst_offset_top - header_h - gap) {
                side_t_b()
            } else {
                side.items.removeClass('yia-fix-top yia-fix-bottom').css('top', '')
            }
            return
        }
        
        if( scrollTop > side_top_menu + side.side_h){
            side_t_b()
        } else {
            side.items.removeClass('yia-fix-top yia-fix-bottom').css('top', '')
        }
    }


    autoLoadArticle(0)
    var side = sideRollInit(gap)
    scrollHandle(function(arg) {
        taggleScrollTop(arg)
        autoLoadArticle(arg)
        catalog_scroll_active(arg)
        side.canRoll && sideRollHandle(arg, side, gap)
    })
})(jQuery);


//////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////

(function($) {

    yiaCtx.event.toggle_top_menu = function(ele, e) {
        ele.next().toggleClass('active')
        $('body').toggleClass('hide')
    }

    $('.yia-top-menu li.menu-item-has-children').each(function () {
        $(this).append('<i class="yiafa toggle_sub">&#xe8d2;</i>')
    })
    
    $('.yia-top-menu li.menu-item-has-children .toggle_sub').on('click', function () {
        $(this).parent().find('>.sub-menu').slideToggle(300)
    })
})(jQuery);



//////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
(function($) {
    yiaCtx.event.toggle_scroll = function(type) {
        type = type ? type : 'hide'
        if(type == 'hide') {
            $('body').addClass('hide')
        } else {
            $('body').removeClass('hide')
        }
    }

    yiaCtx.event.select_change = function(ele, e) {
        var event_handle =  ele.attr('data-event-handle')
        if(event_handle === 'link') {
            document.location.href = ele.val()
        }
    }

    yiaCtx.event.toggle_contact_info = function(ele, e) {
        var body_ele = $('body')
        if(body_ele.hasClass('is-phone') && (body_ele.hasClass('contact-right') || body_ele.hasClass('contact-bottom'))) {
            ele.siblings().find('.contact-info').hide()
            ele.find('.contact-info').toggle()
        }
    }
    
    yiaCtx.event.toggle_search = function(ele, e) {
        var search = $('.header .search-form')
        search.slideToggle('fast', function() {
            search.find('.search-input').focus()
        })
    }
    
    yiaCtx.event.toggle_archive = function(ele, e) {
        ele.toggleClass('active').siblings().slideToggle()
    }

    $(document).on('click change', '[data-event]', function(e) {
        var ele = $(this)
        var event_type =  ele.attr('data-event-type') || 'click'
        if(ele.hasClass('disabled')) {
            return false
        }
        var eventMethod =  ele.attr('data-event')
        if(e.type === event_type && eventMethod && yiaCtx.event[eventMethod]) {
            yiaCtx.event[eventMethod](ele, e)
        }
    })
    
    $(document).ready(function(){
        // 目录
        yiaCtx.event.init_catalog_anchor()
    })
})(jQuery);




//////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
(function($) {

    yiaCtx.event.sign_out = function(ele) {
        $.ajax({
            url: yiaCtx.ajaxUri,
            type: 'GET',
            dataType: 'json',
            data: {
                action: 'sign_out'
            },
            success: function(data) {
                yiaCtx.notice(data.errormsg)
                $('.yia-login').removeClass('logged')
            }
        })
    }

    yiaCtx.event.login = function(ele) {
        var type = ele.attr('data-type')
        var href = ele.attr('data-href')
        var sign_in_href = type == 'sign-in' ? href : ele.siblings('.yia-sign-in').attr('data-href')
        var register_href = type == 'sign-in' ? ele.siblings('.yia-register').attr('data-href') : href
        open_sign_modal(type, sign_in_href, register_href, true, ele.attr('data-refresh'))

    }

    yiaCtx.event.hide_login_modal = function() {
        var login_modal = $('.yia-login-modal')
        login_modal.find('.modal-content').animate({
            top: "100%"
        }, 500, function() {
            login_modal.hide()
            yiaCtx.event.toggle_scroll('show')
        })
    }

    var show_login = $('.show-login')
    if(show_login.length) {
        var href = show_login.attr('data-src')
        if(show_login.attr('data-new')) {
            location.href = href
        } else {
            open_sign_modal('sign-in', href, show_login.attr('data-register'), false, true)
        }
    }
    
    function open_sign_modal(type, sign_in_href, register_href, can_close, refresh) {
        if (window.TBM) { 
            return TBM.login_modal()
        }
        var login_modal = $('.yia-login-modal')
        var btn = yiaCtx.users_can_register ?  '<div class="login-tab-item' + (type == 'sign-in' ? ' active' : '') + '" data-event="login" data-type="sign-in" data-href="' + sign_in_href + '">' + tboslang['1006'] + '</div><div class="login-tab-item' + (type == 'register' ? ' active' : '') + '" data-event="login" data-type="register" data-href="' + register_href + '">' + tboslang['1007'] + '</div>' : ''
        if( !login_modal.length ){
            $('body').append('<div class="yia-login-modal">'
                + '<div class="modal-mask" ' + (can_close ?  'data-event="hide_login_modal"' : '') + '></div>'
                + '<div class="modal-content yia-rds4">'
                    + (can_close ? '<i class="yiafa icon-close" data-event="hide_login_modal">&#xe8e0;</i>' : '')
                    + btn
                + '</div>'
            + '</div>')
        } else {
            login_modal.find('.login-tab-item').removeClass('active')
            login_modal.find('.login-tab-item[data-type=' + type + ']').addClass('active')
        }
        
        var frame = $( '<iframe id="yia-login-iframe" name="yia-login-iframe" frameborder="0" width="98%" height="186px">' )
        frame.on( 'load', function() {
            var body = $( this ).contents().find( 'body' )
            if (!body) { return}
            if(type == 'sign-in' && body.hasClass( 'interim-login-success' )) {
                yiaCtx.notice(tboslang['1008'])
                yiaCtx.event.hide_login_modal()
                $.ajax({
                    url: yiaCtx.ajaxUri,
                    type: 'GET',
                    dataType: 'json',
                    data: {
                        action: 'get_user_info'
                    },
                    success: function(data) {
                        if(!data.info) { return }
                        
                        if( refresh ) {
                            location.reload()
                        } else {
                            var parent = $('.yia-login')
                            parent.find('.avatar').remove()
                            parent.addClass('logged').prepend(data.info.avatar).find('.w-user-name').html(data.info.name)
                        }
                    }
                })
            } else if( type == 'register' && body.hasClass( 'login-action-checkemail' )) {
                var message = body.find('.message')
                var text = message ? message.text() : ''
                if(text && (text.indexOf('注册成功') || text.indexOf('Registration complete'))) {
                    yiaCtx.event.login($('.yia-sign-in'))
                }
            } else {
                var error = body.find('#login_error')
                if(error) {
                    error.find('a').attr('target', '_blank')
                    yiaCtx.notice(error.html(), 'error', 'auto', 3000)
                }
            }
        }).attr( 'src', type == 'sign-in' ? sign_in_href : register_href )

        var cont = $('.modal-content')
        cont.find('iframe').remove()
        $('.yia-login-modal').show()
        cont.append( frame ).animate({top: '50%'}, 500)
        yiaCtx.event.toggle_scroll('hide')
    }
})(jQuery);